package znbkTestPaperNtxl.fragment;

import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.lancooznbk.R;
import com.example.lancooznbk.utils.DialogHelper;
import com.example.lancooznbk.view.base.BaseFragment;
import com.example.lancooznbk.view.widget.ClickImageView;
import com.example.lancooznbk.view.widget.ScaleButton;
import com.google.gson.Gson;
import com.lancoo.rxretrofitlibrary.Api.UserInfo;

import java.util.ArrayList;
import java.util.List;

import lancooControl.AnswerViewPagerAdapter;
import lancooControl.Control;
import lancooCustomListview.BounceListView;
import znbkTopicType.WrapBaseAdapter;
import znbkTestPaperBj.entity.NotePaperEntity;
import znbkTestPaperCtfd.activity.WrongTopicTutoringPaperActivity;
import znbkTestPaperCtfd.entity.WrongTopicTutoringModel;
import znbkTestPaperCtfd.entity.WrongTopicTutoringModelEntity;
import znbkTestPaperInfor.ZnbkPaperDef;
import znbkTestPaperInfor.ZnbkPaperInfor;
import znbkTopicType.NoteDetailActivity;
import znbkTopicType.content.ZnbkContentDxtAdapter;
import znbkTopicType.content.ZnbkContentPptAdapter;
import znbkTopicType.content.ZnbkContentTktAdapter;
import znbkTopicType.content.ZnbkContentTlxzAdapter;
import znbkTopicType.content.ZnbkContentXztAdapter;
import znbkTopicType.content.ZnbkContentZwAdapter;
import znbkTopicType.response.ZnbkResponsePptAdapter;
import znbkTopicType.response.ZnbkResponseTktAdapter;
import znbkTopicType.response.ZnbkResponseXztAdapter;
import znbkTopicType.response.ZnbkResponseJdtAdapter;

import static znbkTestPaperNtxl.activity.TrainingDifficultProblemsPaperActivity.PAPER_FROM;
import static znbkTestPaperNtxl.activity.TrainingDifficultProblemsPaperActivity.mEntityNtxl;

/**
 * Created by Administrator on 2018\2\9 0009.
 */

public class TrainingDifficultProblemsPaperFragment extends BaseFragment {

        private int mNum; //页号
        private ArrayList<View> list;
        private TextView TvContentType;//题目简介
        private BounceListView LvContent;//试题主干部分
        private TextView TvContentNumber;//
        public ViewPager VpAnswer;
        private WrapBaseAdapter mAdapter;
        private int state = 0;//试卷作答状态

        private int layoutId;

        private int mModelFrom;
        private FrameLayout mFlLoading;
        private RelativeLayout relContainer;

        public static boolean IsHaveNoteNtxl = false;
        private TextView mTvTypeName;//题目类型
        private ClickImageView mCivNote;
        private ClickImageView mCivAccessToCounselling;
        private ClickImageView mCivKnowledgePoint;


        public static TrainingDifficultProblemsPaperFragment newInstance(int num) {
                TrainingDifficultProblemsPaperFragment fragment = new TrainingDifficultProblemsPaperFragment();
                Bundle args = new Bundle();
                args.putInt("num", num);
                fragment.setArguments(args);
                return fragment;
        }



        @Override
        public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                //这里我只是简单的用num区别标签，其实具体应用中可以使用真实的fragment对象来作为叶片
                mNum = getArguments() != null ? getArguments().getInt("num") : 1;
                mModelFrom = getHolderActivity().getIntent().getIntExtra(PAPER_FROM,0);
        }

        @Override
        protected void updateViews(boolean isShowLoading) {

                if(getQuesType().equals("作文")||
                        getQuesType().equals("看图写句子")||
                        getQuesType().equals("翻译题")||
                        getQuesType().equals("单选题")){
                        VpAnswer.setVisibility(View.GONE);
                        showCommonTesePaper(false);
                }else{
                        VpAnswer.setVisibility(View.VISIBLE);
                        showCommonTesePaper(true);
                }

                relContainer.post(new Runnable() {
                        @Override
                        public void run() {
                                mFlLoading.setVisibility(View.GONE);
                                if (layoutId == R.layout.paper_zgt||layoutId == R.layout.paper_dxt) {
                                        DialogHelper.showGuideOne(getHolderActivity());
                                        // DialogHelper.showPopup(GuessTestingPaperFragment.this);
                                }else{
                                        DialogHelper.showGuideTwo(getHolderActivity());
                                }
                        }
                });
        }

        @Override
        public int attachLayoutRes() {
                return R.layout.znbk_paper_commonly;
        }


        @Override
        public void initViews(View view, Bundle savedInstanceState) {
                state = mEntityNtxl.getAnswerState();
                Log.e("===111111===888888==", String.valueOf(state));
                mFlLoading = (FrameLayout) view.findViewById(R.id.fl_ques_loading);
                relContainer = (RelativeLayout) view.findViewById(R.id.common_main);
                TvContentType = (TextView) view.findViewById(R.id.textview_content_type);
                TvContentNumber = (TextView) view.findViewById(R.id.textview_content_number);
                LvContent = (BounceListView) view.findViewById(R.id.listview_content);
                VpAnswer = (ViewPager) view.findViewById(R.id.viewpage_answer);

        /*
        * 题目简介(试题)
        * */
                TvContentType.setText("难题");

        /*
        * 匹配题目小题数分布
        * */
                TvContentNumber.setText(Html.fromHtml("<font color='#3399cc'>"+(mNum+1)+"</font>"+"/"+"<font color='#686868'>"+getQusSum()+"</font>"));

         /*
        *笔记相关
        * */
                mTvTypeName = (TextView) view.findViewById(R.id.tv_typeName);
                String GenreName = mEntityNtxl.getTKQue().getGenreName();
                String TypeName = mEntityNtxl.getTKQue().getTypeName();
                if(!GenreName.equals("")){
                        TypeName = GenreName;
                }
                mTvTypeName.setText(TypeName);

                mCivNote = (ClickImageView) view.findViewById(R.id.civ_note);
                mCivAccessToCounselling = (ClickImageView) view.findViewById(R.id.civ_accessToCounselling);
                mCivAccessToCounselling.setClickListener(new ClickImageView.ClickListener() {
                        @Override
                        public void onClick() {


                                List<WrongTopicTutoringModelEntity.StuAnswerBean> jsonAnswerList
                                        = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean>();

                                int TotalItemCount = mEntityNtxl.getTKQue().getTotalItemCount();
                                int QuesItemSize = mEntityNtxl.getTKQue().getChildList().size();
                                if(TotalItemCount==QuesItemSize){

                                        for(int i=0;i<ZnbkPaperInfor.TotalItemCount;i++){

                                                List<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean> jsonSubChildList
                                                        = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean>();

                                                String StuAssess = mEntityNtxl.getTKQue().getChildList().get(i).getSubChildList().get(0).getSubChildStuAssess();
                                                String StuAnswer = mEntityNtxl.getTKQue().getChildList().get(i).getSubChildList().get(0).getSubChildStuAnswer();
                                                String UpLoadPath = mEntityNtxl.getTKQue().getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                                                jsonSubChildList.add(WrongTopicTutoringModel.getSubChildListBean(StuAssess,1,StuAnswer,UpLoadPath));
                                                jsonAnswerList.add(WrongTopicTutoringModel.getStuAnswerBean(i+1,jsonSubChildList));
                                                ZnbkPaperInfor.ListStuAnswerCtfd = jsonAnswerList;
                                        }

                                }else if(TotalItemCount>QuesItemSize){
                                        List<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean> jsonSubChildList
                                                = new ArrayList<WrongTopicTutoringModelEntity.StuAnswerBean.SubChildListBean>();

                                        String StuAssess = mEntityNtxl.getTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildStuAssess();
                                        String StuAnswer = mEntityNtxl.getTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildStuAnswer();
                                        String UpLoadPath = mEntityNtxl.getTKQue().getChildList().get(0).getSubChildList().get(0).getUpLoadPath();
                                        jsonSubChildList.add(WrongTopicTutoringModel.getSubChildListBean(StuAssess,1,StuAnswer,UpLoadPath));
                                        jsonAnswerList.add(WrongTopicTutoringModel.getStuAnswerBean(1,jsonSubChildList));
                                }

                                String QuesID = mEntityNtxl.getTKQue().getQuesID();
                                String CreatTime = mEntityNtxl.getUpdateTime();

                                WrongTopicTutoringPaperActivity.launch(getHolderActivity(),QuesID,CreatTime,jsonAnswerList,ZnbkPaperDef.FROM_WRONG_TOPIC_TUTORING);
                        }
                });
                mCivKnowledgePoint = (ClickImageView) view.findViewById(R.id.civ_knowledgePoint);

                if(mEntityNtxl.getAnswerState()==3){
                        if(mEntityNtxl.getCorrectRate()<0.6){
                                mCivAccessToCounselling.setVisibility(View.VISIBLE);
                        }else{
                                mCivAccessToCounselling.setVisibility(View.GONE);
                        }
                }else{
                        mCivAccessToCounselling.setVisibility(View.GONE);
                }
                mCivKnowledgePoint.setVisibility(View.GONE);
                mCivNote.setVisibility(View.VISIBLE);


                if (!mEntityNtxl.getTKQue().getNoteId().equals("")) {
                        //获取已有学生笔记内容,显示查看图标
                        IsHaveNoteNtxl = true;
                } else {
                        //显示写入笔记图标
                        IsHaveNoteNtxl = false;
                }

                String ResType = mEntityNtxl.getTKQue().getResType();
                final String TypeNo = mEntityNtxl.getTKQue().getTypeNo();
                final String QuesID = mEntityNtxl.getTKQue().getQuesID();
                int NoteFlag= -1;

                if (ResType.equals("Q")) {
                        NoteFlag = 0;
                        ResType = TypeNo;
                } else {
                        NoteFlag = 1;
                }

                if (IsHaveNoteNtxl) {
                        //获取已有学生笔记内容,显示查看图标
                        mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
                } else {
                        //显示写入笔记图标
                        mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
                }

                final int finalNoteFlag = NoteFlag;
                final String finalResType = ResType;
                mCivNote.setClickListener(new ClickImageView.ClickListener() {
                        @Override
                        public void onClick() {
                                getNotesData(QuesID, finalNoteFlag);
                        }
                });

        }

        @Override
        public void onResume() {
                super.onResume();
                if (IsHaveNoteNtxl) {
                        //获取已有学生笔记内容,显示查看图标
                        mCivNote.setBackgroundResource(R.mipmap.znbk_button_check_notes);
                } else {
                        //显示写入笔记图标
                        mCivNote.setBackgroundResource(R.mipmap.znbk_button_no_notes);
                }
        }


        /*
        * @@显示试卷主体
        * 实现试卷界面的布局展示
        * */
        private void showCommonTesePaper(boolean bShowChildViewPager){

//        /*
//        * 题目简介(试题)
//        * */
//        TvContentType.setText(InforDifficultReview.getTypeName());
//
//        /*
//        * 匹配题目小题数分布
//        * */
//        TvContentNumber.setText(Html.fromHtml("<font color='#45a1cf'><big><big>"+(mNum+1)+"</big></big></font>"+"/"+getQusSum()));


         /*
        * 试题主干显示区
        * */

                if(getQuesType().equals("作文")||
                        getQuesType().equals("翻译题")||
                        getQuesType().equals("看图写句子")){
                        mAdapter = new ZnbkContentZwAdapter(getActivity(), 1, mNum,mModelFrom);
                }else if(getQuesType().equals("单选题")) {
                        mAdapter = new ZnbkContentDxtAdapter(getActivity(), 1, mNum,mModelFrom);
                }else if(getQuesType().equals("匹配题")){
                        mAdapter = new ZnbkContentPptAdapter(getActivity(), 1, mNum,mModelFrom);
                }else if(getQuesType().equals("听力选择")||
                        getQuesType().equals("听力简答")||
                        getQuesType().equals("听力填空")){
                        mAdapter = new ZnbkContentTlxzAdapter(getActivity(),1,mNum,mModelFrom);
                }else if(getQuesType().equals("完形选择")||
                        getQuesType().equals("阅读理解")||
                        getQuesType().equals("阅读选择")||
                        getQuesType().equals("阅读判断")){
                        mAdapter = new ZnbkContentXztAdapter(getActivity(),1,mNum,mModelFrom);
                }else if(getQuesType().equals("词汇填空")||
                        getQuesType().equals("改错题")||
                        getQuesType().equals("阅读填空")||
                        getQuesType().equals("阅读简答")||
                        getQuesType().equals("句子填空")||
                        getQuesType().equals("翻译填空")||
                        getQuesType().equals("短文填空")){
                        mAdapter = new ZnbkContentTktAdapter(getActivity(),1,mNum,mModelFrom);
                }
                LvContent.setAdapter(mAdapter);

                if(bShowChildViewPager) {

            /*
            * 答题区
            * */
                        list = new ArrayList<View>();
                        list.clear();
                        int sumSubject = getSubjectSum(mNum);
                        for (int k = 0; k < sumSubject; k++) {

                                BounceListView LvAnswer = new BounceListView(getActivity());
                                if( getQuesType().equals("匹配题")){
                                        LvAnswer.setAdapter(new ZnbkResponsePptAdapter(getActivity(),1,mNum,k,mModelFrom));
                                }else if( getQuesType().equals("词汇填空")||
                                        getQuesType().equals("改错题")||
                                        getQuesType().equals("阅读填空")||
                                        getQuesType().equals("句子填空")||
                                        getQuesType().equals("翻译填空")||
                                        getQuesType().equals("短文填空")||
                                        getQuesType().equals("听力填空")){
                                        LvAnswer.setAdapter(new ZnbkResponseTktAdapter(getActivity(),1,mNum,k,mModelFrom));
                                }else if( getQuesType().equals("听力选择")||
                                        getQuesType().equals("阅读选择")||
                                        getQuesType().equals("阅读判断")||
                                        getQuesType().equals("完形选择")||
                                        getQuesType().equals("阅读理解")){
                                        LvAnswer.setAdapter(new ZnbkResponseXztAdapter(getActivity(),1,mNum,k,mModelFrom));
                                }else if( getQuesType().equals("阅读简答")||
                                           getQuesType().equals("听力简答")){
                                        LvAnswer.setAdapter(new ZnbkResponseJdtAdapter(getActivity(),1,mNum,k,mModelFrom));
                                }
                                list.add(LvAnswer);
                        }

                        VpAnswer.setAdapter(new AnswerViewPagerAdapter(list));
                        VpAnswer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                        //此处添加父页面操作事件
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                        });
                }


        }



        /*
        * 获取试卷总页数
        * */
        private int getQusSum(){
                return 1;
        }

        /*
        * 获取题目对应的小题数目(显示页数)
        * */
        private int getSubjectSum(int position){
                int sumSubject = -1;
                if(getQuesType().equals("改错题")||
                        getQuesType().equals("阅读填空")||
                        getQuesType().equals("词汇填空")){
                        sumSubject = 1;
                }
                else if(mEntityNtxl.getTKQue().getTypeName().equals("匹配题")){
                        sumSubject = Control.backSum(mEntityNtxl.getTKQue().getChildList().get(0).getSubChildList().get(0).getSubChildAnswer(),"$、")+1;
                }
                else {
                        sumSubject = mEntityNtxl.getTKQue().getTotalItemCount();
                }
                return sumSubject;
        }

        private String getQuesType() {
                return mEntityNtxl.getTKQue().getTypeName();
        }


        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
                super.setUserVisibleHint(isVisibleToUser);
                if (!isVisibleToUser && mAdapter != null){//可见时进行调用
                        mAdapter.pause();
                }
        }

        @Override
        public void onStop() {
                super.onStop();
                if (mAdapter != null){//不可见 暂停音乐播放
                        mAdapter.pause();
                }
        }

        @Override
        public void onPause() {
                super.onPause();
                if (mAdapter != null){//不可见 暂停音乐播放
                        mAdapter.pause();
                }
        }

        @Override
        public void onDestroy() {
                super.onDestroy();
                if (mAdapter != null) {
                        mAdapter.stop();
                }
        }


        /*****************************************************************************************************/
        /***查看笔记内容*******/
        PopupWindow popWinNotes = null;
        TextView TvNotes;
        ScaleButton SBtnChangeNotes;
        public PopupWindow showNotesPopupWindow(final View anchorView, final String noteContent,final String noteID) {
                final View contentView = LayoutInflater.from(anchorView.getContext()).inflate(R.layout.znbk_pw_notes, null);
                contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                // 创建PopupWindow时候指定高宽时showAsDropDown能够自适应
                // 如果设置为wrap_content,showAsDropDown会认为下面空间一直很充足（我以认为这个Google的bug）
                // 备注如果PopupWindow里面有ListView,ScrollView时，一定要动态设置PopupWindow的大小
                popWinNotes = new PopupWindow(contentView,
                        contentView.getMeasuredWidth(), contentView.getMeasuredHeight(), false);

                TvNotes = (TextView) contentView.findViewById(R.id.tv_notes);
                TvNotes.setText(noteContent);

                SBtnChangeNotes = (ScaleButton) contentView.findViewById(R.id.sbtn_change_notes);
                SBtnChangeNotes.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                popWinNotes.dismiss();

                                String Title = mEntityNtxl.getTKQue().getQuesBrief();
                                String ResType = mEntityNtxl.getTKQue().getResType();
                                String TypeNo = mEntityNtxl.getTKQue().getTypeNo();
                                String QuesID = mEntityNtxl.getTKQue().getQuesID();
                                if (ResType.equals("Q")) {
                                        ResType = TypeNo;
                                }

                                NoteDetailActivity.launch(getHolderActivity(),noteContent,Title,noteID,ResType,QuesID,
                                        ZnbkPaperDef.FROM_TRAINING_DIFFICULT_PROBLEMS);


                        }
                });

                popWinNotes = new PopupWindow(contentView,
                        FrameLayout.LayoutParams.MATCH_PARENT, contentView.getMeasuredHeight(), false);

                contentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                                // 自动调整箭头的位置
                                autoAdjustArrowPos(popWinNotes, contentView, anchorView);
                                contentView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                });
                // 如果不设置PopupWindow的背景，有些版本就会出现一个问题：无论是点击外部区域还是Back键都无法dismiss弹框
                popWinNotes.setBackgroundDrawable(new ColorDrawable());

                // setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false)
                popWinNotes.setOutsideTouchable(true);

                // 设置为true之后，PopupWindow内容区域 才可以响应点击事件
                popWinNotes.setTouchable(true);

                // true时，点击返回键先消失 PopupWindow
                // 但是设置为true时setOutsideTouchable，setTouchable方法就失效了（点击外部不消失，内容区域也不响应事件）
                // false时PopupWindow不处理返回键
                popWinNotes.setFocusable(true);
//        popWinNotes.setTouchInterceptor(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                return false;   // 这里面拦截不到返回键
//            }
//        });
                // 如果希望showAsDropDown方法能够在下面空间不足时自动在anchorView的上面弹出
                // 必须在创建PopupWindow的时候指定高度，不能用wrap_content
                popWinNotes.showAsDropDown(anchorView);


                return popWinNotes;
        }

        /*****fast-json 解析笔记内容******/
        private void getNotesData(String QuesID,int NoteFlag){

                String url = ZnbkPaperInfor.BaseHttpAdress+"api/ZNBK/W_ZNBK_GetPersonalNote?"+"StuID="+ UserInfo.StuId+
                        "&SubjectID="+UserInfo.SubjectId+"&StageNo="+UserInfo.StageNo+"&QuesID="+QuesID+
                        "&IsReplace=true"+"&Flag="+NoteFlag;

                StringRequest request = new StringRequest(url, new Response.Listener<String>() {
                        @Override
                        public void onResponse(String arg0) {
                                Log.e("==wgl==",""+arg0);//获取完成后，在 http://www.bejson.com/ 解析查看数据
                                dealData(arg0);
                        }
                }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError arg0) {
                                // TODO Auto-generated method stub
                                final String NoteID = mEntityNtxl.getTKQue().getNoteId();
                                String ResType = mEntityNtxl.getTKQue().getResType();
                                String TypeNo = mEntityNtxl.getTKQue().getTypeNo();
                                final String Title = mEntityNtxl.getTKQue().getQuesBrief();
                                final String QuesID = mEntityNtxl.getTKQue().getQuesID();
                                if (ResType.equals("Q")) {
                                        ResType = TypeNo;
                                }
                                NoteDetailActivity.launch(getHolderActivity(),"",Title,NoteID, ResType,QuesID,
                                        ZnbkPaperDef.FROM_TRAINING_DIFFICULT_PROBLEMS);
                        }
                });
                new Volley().newRequestQueue(getContext()).add(request);
        }


        //处理数据
        private void dealData(String result){
                Gson gson = new Gson();
                NotePaperEntity notePaperEntity = gson.fromJson(result, NotePaperEntity.class); // data 转实体
                String NoteContent = notePaperEntity.getModelNoteList().getContent();
                String NoteID = notePaperEntity.getModelNoteList().getNoteID();

                if(!NoteContent.equals("")) {
                        showNotesPopupWindow(mCivNote,NoteContent,NoteID);
                }

        }

        private void autoAdjustArrowPos(PopupWindow popupWindow, View contentView, View anchorView) {
                View upArrow = contentView.findViewById(R.id.up_arrow);
                View downArrow = contentView.findViewById(R.id.down_arrow);

                int pos[] = new int[2];
                contentView.getLocationOnScreen(pos);
                int popLeftPos = pos[0];
                anchorView.getLocationOnScreen(pos);
                int anchorLeftPos = pos[0];
                int arrowLeftMargin = anchorLeftPos - popLeftPos + anchorView.getWidth() / 2 - upArrow.getWidth() / 2;
                upArrow.setVisibility(popupWindow.isAboveAnchor() ? View.INVISIBLE : View.VISIBLE);
                downArrow.setVisibility(popupWindow.isAboveAnchor() ? View.VISIBLE : View.INVISIBLE);

                RelativeLayout.LayoutParams upArrowParams = (RelativeLayout.LayoutParams) upArrow.getLayoutParams();
                upArrowParams.leftMargin = arrowLeftMargin;
                RelativeLayout.LayoutParams downArrowParams = (RelativeLayout.LayoutParams) downArrow.getLayoutParams();
                downArrowParams.leftMargin = arrowLeftMargin;
        }

/**************************************************************************************************************************/

}